<?php
namespace app\api\controller;
/**
 * 对象存储OSS 文件上传
 * User: huangzhen
 * Date: 2021/03/02
 */

use think\facade\Request;
use lemo\api\Api;
use think\facade\Db;
use org\upload\driver\Aliyun;

class OssUp
{
    /**
     * 构造方法
     * @param Request $request Request对象
     */
    public function __construct(Request $request)
    {
    }

    public static function fileUp($data , $suffix)
    {
        $type           = $data['type'];
        //获取key和secret
        $accessKeyId        = decryptOpenssl('37IMoCNbgge1Xcm1hezFwwU4oeSVbi0n9pzQuRv8dAM=');
        $accessKeySecret    = decryptOpenssl('oxw4rwffNN2UDdgkW13MVWcDXfgJsjCquF+hbX/UuQU=');
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-us-west-1.aliyuncs.com";
        // 设置存储空间名称。
        $bucket= "betterepay";
        // 设置文件名称。
        //work=工单,cz=充值,tx=提现,public=公共
        $object = "{$type}_" . date('YmdHis') . rand(1000,9999) . ".{$suffix}";
        // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        //$filePath = ROOT_PATH . "/storage/uploads/20210121/4abca6aade05c2593d061a7dfe50d29.jpg";

        $ossClient = new Aliyun([
            'accessKeyId'       => $accessKeyId,
            'accessKeySecret'   => $accessKeySecret,
            'endpoint'          => $endpoint,
            'bucket'            => $bucket
        ]);
        $data += ['save_name'  => $object];
        $re = $ossClient->saveUp($data);

        $url        = "";
        $blog       = true;
        if($re){
            $url        = $re;
            $http_code  = 200;
        }else{
            $blog       = false;
            $http_code  = 500;
        }
//        Db::name('api_other')->save([
//            'name'    => "img_up",
//            'url'     => $endpoint,
//            'ip'      => ip(),
//            'desc'    => "{$type} img up",
//            'code'    => $http_code,
//            'response'=> is_array($re)?json_encode($re):$re,
//        ]);
        return [
            'blog'      => $blog,
            'img_url'   => $url
        ];
    }
}